package immodels

import (
	"context"
	"github.com/zeromicro/go-zero/core/stores/mon"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
	"time"
)

var _ UserConversationModel = (*customUserConversationModel)(nil)

type (
	// UserConversationModel is an interface to be customized, add more methods here,
	// and implement the added methods in customUserConversationModel.
	UserConversationModel interface {
		userConversationModel
		FindByUserId(ctx context.Context, cid string) (*UserConversation, error)
		InsertOrUpdate(ctx context.Context, data *UserConversation) error
	}

	customUserConversationModel struct {
		*defaultUserConversationModel
	}
)

// NewUserConversationModel returns a model for the mongo.
func NewUserConversationModel(url, db, collection string) UserConversationModel {
	conn := mon.MustNewModel(url, db, collection)
	return &customUserConversationModel{
		defaultUserConversationModel: newDefaultUserConversationModel(conn),
	}
}

// FindByUserId 根据用户ID查找用户对应的会话列表
func (m *customUserConversationModel) FindByUserId(ctx context.Context, cid string) (*UserConversation, error) {
	var data UserConversation

	err := m.conn.FindOne(ctx, &data, bson.M{"userId": cid})
	switch err {
	case nil:
		return &data, nil
	case mon.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (m *customUserConversationModel) InsertOrUpdate(ctx context.Context, data *UserConversation) error {
	data.UpdateAt = time.Now()
	_, err := m.conn.UpdateOne(ctx, bson.M{"_id": data.ID}, bson.M{"$set": data}, options.Update().SetUpsert(true))
	return err
}
